package com.sip.stream.utils.zfy.consumer;

import android.media.MediaFormat;
import android.os.Handler;
import android.os.HandlerThread;
import android.os.Message;
import android.util.Log;

import com.sip.stream.media.ZFYMediaManager;
import com.sip.stream.utils.zfy.GSMediaSampleData;
import com.sip.stream.utils.zfy.ZFYFilePath;
import com.sip.stream.utils.zfy.encoder.IGSAudioEncoder;
import com.sip.stream.utils.zfy.encoder.IGSVideoEncoder;
import com.sip.stream.utils.zfy.muxer.BarSteamTool;
import com.sip.stream.utils.zfy.muxer.GSBareStreamWriter;
import com.sip.stream.utils.zfy.muxer.GSMp4Muxer;
import com.sip.stream.utils.zfy.muxer.ZFYPreRecordConsumer;
import com.sip.stream.utils.zfy.muxer.ZFYPreRecordReader;
import com.sip.stream.utils.zfy.status.ZFYStatus;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.util.Date;

public class ZFYMp4Consumer implements IGSVideoConsumer {
    private static final String TAG = "ZFYMp4Consumer";

    private static final int WHAT_ADD = 1;
    private static final int WHAT_CACHE_FORMATE = 6;
    private static final int WHAT_CHECK_STATUS = 5;
    private static final int WHAT_STOP = 4;
    private static final int WHAT_SWITCH = 2;
    private IGSMediaObserver<IGSAudioEncoderConsumer> audioEncoderConsumerObserver;
    private IGSAudioEncoderConsumer audioEncoderLisener;
    private MediaFormat audioFormat;
    private GSBareStreamWriter backUpMuxer;
    private HandlerThread backgroundThread;
    private Handler handler;
    private GSMp4Muxer muxer;
    private boolean needSwitch;
    private int sepTimeSecond;
    private MediaFormat vdieoFormat;
    private IGSMediaObserver<IGSVideoEncoderConsumer> videoEncoderConsumerObserver;
    private IGSVideoEncoderConsumer videoEncoderLisener;

    @Override
    public void start() {
    }

    public ZFYMp4Consumer(IGSVideoEncoder iGSVideoEncoder, IGSAudioEncoder iGSAudioEncoder) {
        this.needSwitch = false;
        this.muxer = new GSMp4Muxer(ZFYMediaManager.getInstance().createNewRecording(1));
        setUp(0L, iGSVideoEncoder, iGSAudioEncoder);
        if (ZFYStatus.getInstance().isBatteryin()) {
            return;
        }
        switchBackup(true);
    }

    public ZFYMp4Consumer(ZFYPreRecordConsumer zFYPreRecordConsumer) {
        this.needSwitch = false;
        zFYPreRecordConsumer.stopAction();
        GSMp4Muxer gSMp4Muxer = new GSMp4Muxer(ZFYMediaManager.getInstance().createNewRecording(1), new ZFYPreRecordReader(zFYPreRecordConsumer));
        this.muxer = gSMp4Muxer;
        gSMp4Muxer.addVideoTrack(zFYPreRecordConsumer.getVideoOutputFormat());
        this.muxer.addAudioTrack(zFYPreRecordConsumer.getAudioOutputFormat());
        IGSVideoEncoder videoEncoder = zFYPreRecordConsumer.getVideoEncoder();
        videoEncoder.setForcedInterval(0);
        IGSAudioEncoder audioEncoder = zFYPreRecordConsumer.getAudioEncoder();
        Date date = new Date();
        long videoPreTime = ZFYMediaManager.getInstance().getConfig().getVideoPreTime() * 1000;
        Date startDate = zFYPreRecordConsumer.getStartDate();
        if (date.getTime() - zFYPreRecordConsumer.getStartDate().getTime() > videoPreTime) {
            startDate = new Date(date.getTime() - videoPreTime);
        } else {
            videoPreTime = zFYPreRecordConsumer.getStartDate().getTime() - date.getTime();
        }
        ZFYMediaManager.getInstance().getStatus().setBeginRecordingDate(startDate);
        ZFYMediaManager.getInstance().getStatus().setLastRecordingDate(startDate);
        setUp(videoPreTime, videoEncoder, audioEncoder);
        zFYPreRecordConsumer.release();
    }

    private void setUp(long j, IGSVideoEncoder iGSVideoEncoder, IGSAudioEncoder iGSAudioEncoder) {
        setUpListener(iGSVideoEncoder, iGSAudioEncoder);
        int videoSepTime = ZFYMediaManager.getInstance().getConfig().getVideoSepTime();
        this.sepTimeSecond = videoSepTime;
        if (videoSepTime > 0) {
            getHandler().sendEmptyMessageDelayed(2, (((this.sepTimeSecond * 60) - (j / 1000)) * 1000) - 500);
        }
    }

    public Handler getHandler() {
        if (this.handler == null) {
            HandlerThread handlerThread = new HandlerThread("CameraBackground");
            this.backgroundThread = handlerThread;
            handlerThread.start();
            this.handler = new Handler(this.backgroundThread.getLooper(), new Handler.Callback() {
                @Override
                public  boolean handleMessage(Message message) {
                    return ZFYMp4Consumer.this.m522x22892c03(message);
                }
            });
        }
        return this.handler;
    }

    public  boolean m522x22892c03(Message message) {
        int i = message.what;
        if (i == 2) {
            this.needSwitch = true;
            return false;
        } else if (i == 4) {
            stopMuxer();
            return false;
        } else if (i != 6) {
            return false;
        } else {
            try {
                cacheFormat();
                return false;
            } catch (Exception e) {
                e.printStackTrace();
                return false;
            }
        }
    }

    private void setUpListener(IGSVideoEncoder iGSVideoEncoder, IGSAudioEncoder iGSAudioEncoder) {
        IGSAudioEncoderConsumer iGSAudioEncoderConsumer = new IGSAudioEncoderConsumer() {
            @Override
            public void encodeAudioError(String str) {
            }

            @Override
            public void encodeAudioSuccess(GSMediaSampleData gSMediaSampleData) {
                ZFYMp4Consumer.this.writeSampleData(gSMediaSampleData);
            }

            @Override
            public void setOutputFormat(MediaFormat mediaFormat) {
                ZFYMp4Consumer.this.muxer.addAudioTrack(mediaFormat);
                ZFYMp4Consumer.this.audioFormat = mediaFormat;
                ZFYMp4Consumer.this.getHandler().sendEmptyMessage(6);
            }

            @Override
            public void addObserver(IGSMediaObserver<IGSAudioEncoderConsumer> iGSMediaObserver) {
                ZFYMp4Consumer.this.audioEncoderConsumerObserver = iGSMediaObserver;
            }
        };
        this.audioEncoderLisener = iGSAudioEncoderConsumer;
        iGSAudioEncoder.addLisener(iGSAudioEncoderConsumer);
        IGSVideoEncoderConsumer iGSVideoEncoderConsumer = new IGSVideoEncoderConsumer() {
            @Override
            public void encodeVideoError(String str) {
            }

            @Override
            public void encodeVideoSuccess(GSMediaSampleData gSMediaSampleData) {
                ZFYMp4Consumer.this.writeSampleData(gSMediaSampleData);
            }

            @Override
            public void setOutputFormat(MediaFormat mediaFormat) {
                ZFYMp4Consumer.this.muxer.addVideoTrack(mediaFormat);
                ZFYMp4Consumer.this.vdieoFormat = mediaFormat;
                ZFYMp4Consumer.this.getHandler().sendEmptyMessage(6);
            }

            @Override
            public void addObserver(IGSMediaObserver<IGSVideoEncoderConsumer> iGSMediaObserver) {
                ZFYMp4Consumer.this.videoEncoderConsumerObserver = iGSMediaObserver;
            }
        };
        this.videoEncoderLisener = iGSVideoEncoderConsumer;
        iGSVideoEncoder.addLisener(iGSVideoEncoderConsumer);
    }

    @Override
    public void stop() {
        stopMuxer();
    }

    @Override
    public void stop(boolean z) {
        if (!z) {
            stop();
            return;
        }
        getHandler().removeMessages(4);
        stopMuxer();
    }

    private void stopMuxer() {
        if (this.audioEncoderConsumerObserver != null) {
            Log.i(TAG, "audioEncoderConsumerObserver onStop");
            this.audioEncoderConsumerObserver.onStop(this.audioEncoderLisener);
            this.audioEncoderConsumerObserver = null;
        }
        if (this.videoEncoderConsumerObserver != null) {
            Log.i(TAG, "videoEncoderConsumerObserver onStop");
            this.videoEncoderConsumerObserver.onStop(this.videoEncoderLisener);
            this.videoEncoderConsumerObserver = null;
        }
        GSMp4Muxer gSMp4Muxer = this.muxer;
        if (gSMp4Muxer != null) {
            gSMp4Muxer.stop();
            this.muxer = null;
        }
        Handler handler = this.handler;
        if (handler != null) {
            handler.removeCallbacksAndMessages(null);
            this.handler = null;
        }
        HandlerThread handlerThread = this.backgroundThread;
        if (handlerThread != null) {
            handlerThread.interrupt();
            this.backgroundThread = null;
        }
    }

    public synchronized void writeSampleData(GSMediaSampleData gSMediaSampleData) {
        if (this.needSwitch && !gSMediaSampleData.isAudio() && gSMediaSampleData.getBufferInfo().flags == 1) {
            Log.w(TAG, "switchMuxer success");
            this.needSwitch = false;
            /*if (ApplicationConfig.isSongjian) {
                this.muxer.writeSampleData(gSMediaSampleData);
            }*/
            this.muxer.stop();
            GSMp4Muxer gSMp4Muxer = new GSMp4Muxer(ZFYMediaManager.getInstance().createNewRecording(1));
            this.muxer = gSMp4Muxer;
            gSMp4Muxer.addVideoTrack(this.vdieoFormat);
            this.muxer.addAudioTrack(this.audioFormat);
            if (this.sepTimeSecond > 0) {
                getHandler().sendEmptyMessageDelayed(2, ((this.sepTimeSecond * 1000) * 60) - 500);
                Log.w(TAG, "send WHAT_SWITCH " + this.sepTimeSecond);
            }
            ZFYMediaManager.getInstance().getStatus().setBeginRecordingDate(new Date());
        }
        GSMp4Muxer gSMp4Muxer2 = this.muxer;
        if (gSMp4Muxer2 != null) {
            gSMp4Muxer2.writeSampleData(gSMediaSampleData);
        }
        GSBareStreamWriter gSBareStreamWriter = this.backUpMuxer;
        if (gSBareStreamWriter != null) {
            gSBareStreamWriter.writeSampleData(gSMediaSampleData);
        }
    }

    private synchronized boolean switchMuxer() {
        this.needSwitch = false;
        this.muxer.stop();
        GSMp4Muxer gSMp4Muxer = new GSMp4Muxer(ZFYMediaManager.getInstance().createNewRecording(1));
        this.muxer = gSMp4Muxer;
        gSMp4Muxer.addVideoTrack(this.vdieoFormat);
        this.muxer.addAudioTrack(this.audioFormat);
        if (this.sepTimeSecond > 0) {
            getHandler().sendEmptyMessageDelayed(2, ((this.sepTimeSecond * 1000) * 60) - 500);
            Log.w(TAG, "send WHAT_SWITCH " + this.sepTimeSecond);
        }
        ZFYMediaManager.getInstance().getStatus().setBeginRecordingDate(new Date());
        return true;
    }

    @Override
    public void switchBackup(boolean z) {
        if (z) {
            GSBareStreamWriter gSBareStreamWriter = new GSBareStreamWriter(ZFYFilePath.getBarstreamBackupPath() + ZFYMediaManager.getInstance().getNewFileName());
            this.backUpMuxer = gSBareStreamWriter;
            gSBareStreamWriter.start();
            return;
        }
        this.backUpMuxer = null;
    }

    @Override
    public void forceSwitchMuxer() {
        getHandler().removeMessages(4);
        ZFYMediaManager.getInstance().getStatus().setDlayRecording(false);
        getHandler().removeMessages(2);
        getHandler().sendEmptyMessage(2);
        Log.w(TAG, "send forceSwitchMuxer");
    }

    @Override
    public boolean canStop() {
        GSMp4Muxer gSMp4Muxer = this.muxer;
        if (gSMp4Muxer != null) {
            return gSMp4Muxer.canStop();
        }
        return true;
    }

    public void cacheFormat() throws IOException {
        MediaFormat mediaFormat = this.vdieoFormat;
        if (mediaFormat == null || this.audioFormat == null || mediaFormat.getByteBuffer("csd-0") == null || this.audioFormat.getByteBuffer("csd-0") == null) {
            return;
        }
        File file = new File(ZFYFilePath.getFormatCacheDirPath() + "mp4muxer.format");
        if (file.exists()) {
            file.delete();
        }
        FileOutputStream fileOutputStream = new FileOutputStream(file);
        Log.w(TAG, this.vdieoFormat.toString());
        ByteBuffer duplicate = this.vdieoFormat.getByteBuffer("csd-0").duplicate();
        int remaining = duplicate.remaining();
        byte[] bArr = new byte[remaining];
        duplicate.get(bArr);
        fileOutputStream.write(BarSteamTool.int2Bytes(remaining));
        fileOutputStream.write(bArr);
        if (this.vdieoFormat.getByteBuffer("csd-1") != null) {
            ByteBuffer duplicate2 = this.vdieoFormat.getByteBuffer("csd-1").duplicate();
            int remaining2 = duplicate2.remaining();
            byte[] bArr2 = new byte[remaining2];
            duplicate2.get(bArr2);
            fileOutputStream.write(BarSteamTool.int2Bytes(remaining2));
            fileOutputStream.write(bArr2);
        }
        Log.w(TAG, this.audioFormat.toString());
        ByteBuffer duplicate3 = this.audioFormat.getByteBuffer("csd-0").duplicate();
        int remaining3 = duplicate3.remaining();
        byte[] bArr3 = new byte[remaining3];
        duplicate3.get(bArr3);
        fileOutputStream.write(BarSteamTool.int2Bytes(remaining3));
        fileOutputStream.write(bArr3);
        fileOutputStream.flush();
        fileOutputStream.close();
    }
}
